package com.ouman.pure;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;


/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements LoginFragment.OnFragmentInteractionListener, RegisterFragment.OnFragmentInteractionListener{


    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_login);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("登录");
//        getFragmentManager().beginTransaction().replace(R.id.fragment_container_login, new LoginFragment()).commit();

        // 开始巡查权限
        verifyStoragePermissions(LoginActivity.this);

        // 一开始的时候还是检查一下是否已经登陆，如果已经登陆了就直接跳转主页
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
        Boolean isLogin = preferences.getBoolean("isLogin", false);
        if (!isLogin){
            System.out.println("-----!!! 没有登陆调准到登陆的fragment");
            getFragmentManager().beginTransaction().replace(R.id.fragment_container_login, new LoginFragment()).commit();
        }else{
            // 直接跳转到main
            Intent main = new Intent(LoginActivity.this, MainActivity.class);
            LoginActivity.this.startActivity(main);
            finish();
        }
    }

    // Storage Permissions
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    //实现fragment监听方法
    public void onFragmentInteraction(Uri uri){

    }

}

